package com.cxf.windex.rest;

import com.cxf.windex.base.msg.ObjectRestResponse;
import com.cxf.windex.base.msg.TableResultResponse;
import com.cxf.windex.base.rest.BaseRestController;
import com.cxf.windex.base.util.WxUtil;
import com.cxf.windex.base.vo.Pie;
import com.cxf.windex.biz.CxfPlatformBiz;
import com.cxf.windex.entity.CxfPlatform;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

/**
 * @author chenxf
 * @date 5/10/2018
 * @description
 */
@Api(tags = {"聚能小宝 - 平台接口"})
@Controller
@RequestMapping("api_platform")
public class CxfPlatformController extends BaseRestController<CxfPlatformBiz, CxfPlatform> {

  /**
   * 文件存放 路径
   */
  @Value("${upload.path}")
  private String uploadPath;

  /**
   * 文件访问路径
   */
  @Value("${upload.url}")
  private String uploadUrl;

  /**
   * 文件访问域名
   */
  @Value("${upload.uri}")
  private String uploadUri;

  @ApiOperation(value = "获取平台推广码", notes = "获取平台推广码")
  @RequestMapping(value = "/code", method = RequestMethod.GET)
  @ResponseBody
  public TableResultResponse<CxfPlatform> user(@RequestParam(defaultValue = "10") int limit,
      @RequestParam(defaultValue = "1") int offset,
      @RequestParam(defaultValue = "desc") String orderStr) {
    String userId = this.getCurrentUserId();
    Example example = new Example(CxfPlatform.class);
    Criteria criteria = example.createCriteria();
    example.setOrderByClause("id  desc");
    List<CxfPlatform> items = baseBiz.selectByExample(example);

    items.forEach(e -> e.setMinaCode(saveMinaCode(e, userId)));
    PageInfo<CxfPlatform> pageInfo = new PageInfo<CxfPlatform>(items);
    return new TableResultResponse<CxfPlatform>(
        Integer.parseInt(String.valueOf(pageInfo.getTotal())),
        offset, limit,
        items);
  }

  @ApiOperation(value = "获取平台信息", notes = "获取平台信息")
  @RequestMapping(value = "/list", method = RequestMethod.GET)
  @ResponseBody
  public TableResultResponse<CxfPlatform> getInfo(@RequestParam(defaultValue = "10") int limit,
      @RequestParam(defaultValue = "1") int offset,
      @RequestParam(defaultValue = "desc") String orderStr) {
    Example example = new Example(CxfPlatform.class);
    Criteria criteria = example.createCriteria();
    example.setOrderByClause("id  desc");
    PageHelper.startPage(offset, limit);
    List<CxfPlatform> items = baseBiz.selectByExample(example);

    PageInfo<CxfPlatform> pageInfo = new PageInfo<CxfPlatform>(items);
    return new TableResultResponse<CxfPlatform>(
        Integer.parseInt(String.valueOf(pageInfo.getTotal())),
        offset, limit,
        items);
  }

  @ApiOperation(value = "获取平台统计", notes = "获取平台统计信息")
  @RequestMapping(value = "/count", method = RequestMethod.GET)
  @ResponseBody
  public ObjectRestResponse count(int type) {
    List<Pie> result=new ArrayList<Pie>();
    switch (type) {
      case 1:
        result= baseBiz.selectHy();
        break;
      case 2:
        result=baseBiz.selectRz();
        break;
      case 3:
        result=baseBiz.selectPay();
        break;
      default:
        logger.error("传入错误的参数={}",type);
        return new ObjectRestResponse().rel(false).msg("查询失败");

    }
    List<String> nameList = result.stream()
        .map(Pie::getName)
        .collect(Collectors.toList()), countList = result.stream()
        .map(Pie::getCount)
        .collect(Collectors.toList());
    Object[] arrayResult=new Object[]{nameList,countList};
    return new ObjectRestResponse().rel(true).msg("查询成功").result(arrayResult);
  }

  @ApiOperation(value = "保存平台信息", notes = "保存当前平台信息")
  @RequestMapping(value = "/save", method = RequestMethod.POST)
  @ResponseBody
  public ObjectRestResponse save(CxfPlatform platform) {
    if (platform.getId() == null || platform.getId() == 0) {

      baseBiz.insertSelective(platform);
    } else {
      baseBiz.updateSelectiveById(platform);
    }
    return new ObjectRestResponse().rel(true).msg("保存成功");
  }

  private String saveMinaCode(CxfPlatform platform, String userId) {
    String webRoot =
        uploadPath + File.separator + "mina" + File.separator + platform.getId() + File.separator;
    String saveUrl =
        uploadUri + uploadUrl + "/mina/" + platform.getId() + File.separator + userId + ".jpg";
    File directoryFile = new File(webRoot);
    if (!directoryFile.exists()) {
      directoryFile.mkdirs();
    }
    File codeFile = new File(webRoot + userId + ".jpg");
    if (codeFile.exists()) {
      return saveUrl;
    }
    Path path = Paths.get(webRoot + userId + ".jpg");
    try {
      Map<String, String> map = new HashMap<>(2);
      map.put("scene", platform.getSence() + userId);
      byte[] codeBytes = WxUtil.getMinaCodeB(platform.getAppid(), platform.getSecret(), map);
      Files.write(path, codeBytes);

    } catch (IOException e) {
      e.printStackTrace();
    }
    return saveUrl;
  }
}
